package service.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import db.MyHibernateSessionFactory;
import entity.Sponsor;
import service.SponsorDAO;

public class SponsorDAOImpl implements SponsorDAO{

	@Override
	public boolean sponsorRegister(Sponsor sp) {
		Transaction tx = null;
		Session session = MyHibernateSessionFactory.getSessionFactory().getCurrentSession();
		 try {
			tx = session.beginTransaction();
			session.save(sp);
			tx.commit();
			return true;
			 
		} catch (Exception e) {
			// TODO: handle exception
			if(tx != null) tx.rollback();
			e.printStackTrace();
			return false;
		}
		finally{
			 tx = null;
		}
	}


	@Override
	public Sponsor sponsorLogin(Sponsor sp) {
		Transaction tx = null;
		String hql = "";
		Session session = MyHibernateSessionFactory.getSessionFactory().getCurrentSession();
		try {
			tx = session.beginTransaction();
			hql = "from Sponsor where sponsor_email=? and sponsor_password=? ";
			Query query = session.createQuery(hql);
			query.setParameter(0, sp.getSponsorEmail());
			query.setParameter(1, sp.getSponsorPassword());
			List list = query.list();
			tx.commit();
			if(list.size() > 0)
			{
				sp = (Sponsor)list.get(0);
				return sp;
			}
			else{
//					System.out.println("false");
				return null;
			}
		} catch (Exception e) {
			if(tx!=null)	tx.rollback();
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public boolean sponsorLogout(Sponsor sp) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean update(Sponsor sp) {
		Transaction tx = null;
		Session session = MyHibernateSessionFactory.getSessionFactory().getCurrentSession();
		try {
			tx = session.beginTransaction();
			session.update(sp);
			tx.commit();
			return true;
			
		} catch (Exception e) {
			// TODO: handle exception
			if(tx!=null)	tx.rollback();
			e.printStackTrace();
			return false;
		}
		finally{
			tx = null;
		}
	}
	
	@Override
	public Sponsor queryBySponsor_id(int sponsor_id) {
		Transaction tx = null;
		Sponsor tempSp = null;
		Session session = MyHibernateSessionFactory.getSessionFactory().getCurrentSession();
		 try {
			tx = session.beginTransaction();
			tempSp = (Sponsor)session.get(Sponsor.class, sponsor_id);
			
			tx.commit();
			return tempSp;
			 
		} catch (Exception e) {
			// TODO: handle exception
			if(tx != null) tx.rollback();
			e.printStackTrace();
			return tempSp;
		}
		finally{
//			 session.close();
		}
	}
	public static void main(String[] args) {
		Sponsor s = new SponsorDAOImpl().queryBySponsor_id(1);
		System.out.println(s.getSponsorName());
	}
	
}
